﻿using System.Globalization;

namespace Ly.EBussiness.Common.DapperUtils.Page
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class QueryPageBase : QueryBase
    {
        private const int DefaultMaxResultCount = 15;
        private const int DefaultSkipCount = 0;

        /// <summary>
        /// 单页容量
        /// </summary>
        public int MaxResultCount { get; set; } = DefaultMaxResultCount;

        /// <summary>
        /// 当前页码
        /// </summary>
        public int SkipCount { get; set; } = DefaultSkipCount;

        /// <summary>
        /// 提供核心分页总数查询sql 只需要提供 From 往后的sql即可
        /// </summary>
        /// <returns></returns>
        public abstract string GetPageSelectTotalSql();

        /// <summary>
        /// 构建分页总数查询sql
        /// </summary>
        /// <returns></returns>
        public string BuildSelectPageTotalSql()
        {
            InitCondition();
            var selectSql = GetPageSelectTotalSql();
            if (!selectSql.TrimStart().StartsWith("from", true, CultureInfo.CurrentCulture))
                throw new Exception("分页查询获取总记录时,只需要提供From xxx 的语句即可");
            return $"select count(1) TotalCount {selectSql} {GetWhereString()}";
        }

        /// <summary>
        /// 构建分页查询sql
        /// </summary>
        /// <returns></returns>
        public virtual string BuildSelectPageSql()
        {
            InitCondition();
            if (Sorts == null || Sorts?.Count <= 0) throw new Exception("分页查询时,排序条件不可为空");
            var sql = BuildSelectSql();
            var tempMaxResultCount = MaxResultCount <= 0 ? DefaultMaxResultCount : MaxResultCount;
            var tempSkipCount = (SkipCount <= 0 ? DefaultSkipCount : SkipCount - 1) * MaxResultCount;
            return sql + $" Limit {tempSkipCount},{tempMaxResultCount}";
        }
    }
}